package com.epu.itepu;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.epu.itepu.helper.AlbumStorageDirFactory;
import com.epu.itepu.helper.BaseAlbumDirFactory;
import com.epu.itepu.helper.FroyoAlbumDirFactory;
import com.epu.itepu.helper.GPSTracker;
import com.epu.itepu.helper.MyExif;
import com.epu.itepu.helper.Variables;
import com.epu.itepu.models.PhotoProperties;

@SuppressWarnings("deprecation")
public class MainActivity extends TabActivity implements OnTabChangeListener,
		OnItemClickListener {
	
	private TabHost tabHost;
	private GridView gridView;
	private ImageAdapter imageAdapter;
	private Display display;
	private Button btnUp;
	private Button btnCamera;
	private PhotoActivity currentPhotoActivity;

	// variables capture
	private static final int ACTION_TAKE_PHOTO = 1;
	private String mCurrentPhotoPath;
	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";
	private AlbumStorageDirFactory mAlbumStorageDirFactory = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_main);
		gridView = (GridView) findViewById(R.id.gridView);
		
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
		} else {
			mAlbumStorageDirFactory = new BaseAlbumDirFactory();
		}

		tabHost = getTabHost();
		tabHost.getLayoutParams().height = getWindowManager()
				.getDefaultDisplay().getHeight() / 2;

		TabHost.TabSpec spec;
		Intent intent;

		tabHost.setOnTabChangedListener(this);
		intent = new Intent().setClass(this, PhotoActivity.class);
		View tabView = createTabView(this, "Photo");
		spec = tabHost.newTabSpec("Photo").setIndicator(tabView)
				.setContent(intent);
		tabHost.addTab(spec);

		tabView = createTabView(this, "GPS");
		intent = new Intent().setClass(this, GPSActivity.class);
		spec = tabHost.newTabSpec("GPS").setIndicator(tabView)
				.setContent(intent);
		tabHost.addTab(spec);

		tabView = createTabView(this, "Info");
		intent = new Intent().setClass(this, InfoActivity.class);
		spec = tabHost.newTabSpec("Info").setIndicator(tabView)
				.setContent(intent);
		tabHost.addTab(spec);
		
		display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();
		
		//button camera
		btnCamera = (Button) findViewById(R.id.btnCamera);

		btnCamera.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
			}
		});

		//button up
		btnUp = (Button) findViewById(R.id.btnFullGrid);
		btnUp.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if (tabHost.isShown()){
					tabHost.setVisibility(View.GONE);
					MainActivity.this.btnUp.setBackgroundResource(R.drawable.button_down);
				}else{
					tabHost.setVisibility(View.VISIBLE);
					MainActivity.this.btnUp.setBackgroundResource(R.drawable.button_up);
				}
				
			}
		});
		

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			final Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == RESULT_OK) {

			if (mCurrentPhotoPath != null) {
				// Add photo to gallery
				Intent mediaScanIntent = new Intent(
						"android.intent.action.MEDIA_SCANNER_SCAN_FILE");
				
				GPSTracker gpsTracker = new GPSTracker(MainActivity.this);
				if (gpsTracker.canGetLocation()){

					ExifInterface exif;
					try {
						exif = new ExifInterface(mCurrentPhotoPath);
			            exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, gpsTracker.getLatitude());
			            exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, gpsTracker.getLatitudeRef());
			            exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, gpsTracker.getLongitude());
			            exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, gpsTracker.getLongitudeRef());
			            exif.saveAttributes();
					} catch (IOException e) {
						Toast.makeText(getApplication(), "Eror set GPS", Toast.LENGTH_SHORT).show();
					}
				}else{
		            gpsTracker.showSettingsAlert();
		        }
				
				File f = new File(mCurrentPhotoPath);
				Uri contentUri = Uri.fromFile(f);
				mediaScanIntent.setData(contentUri);
				this.sendBroadcast(mediaScanIntent);
				mCurrentPhotoPath = null;
				Debug.startMethodTracing("Pictures/Electric");
				Toast.makeText(this, "luu thanh cong", Toast.LENGTH_SHORT).show();
			}
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		// Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
		/*----------------------set grid photo---------------*/
		setupViews();
		setProgressBarIndeterminateVisibility(true);
		if (!Variables.listProperties.isEmpty()){
			Variables.listProperties.clear();
		}
		if (!Variables.listPhotos.isEmpty()){
			Variables.listPhotos.clear();
			Variables.photoPagerAdapter.notifyDataSetChanged();
		}
		loadImages();
		//get child class
		int tabIndex = tabHost.getCurrentTab();
		if (tabIndex == 0){
			currentPhotoActivity = (PhotoActivity) tabHost.getCurrentView().getContext();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		// Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show();
	}

	private static View createTabView(Context context, String tabText) {
		View view = LayoutInflater.from(context).inflate(R.layout.custom_tab,
				null, false);
		TextView tv = (TextView) view.findViewById(R.id.tabTitleText);
		tv.setText(tabText);
		return view;
	}

	@Override
	public void onTabChanged(String tabId) {
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
		int columnIndex = 0;
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(
				MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection,
				null, null, null);
		if (cursor != null) {
			columnIndex = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToPosition(position);
			String imagePath = cursor.getString(columnIndex);

			FileInputStream is = null;
			BufferedInputStream bis = null;
			try {
				is = new FileInputStream(new File(imagePath));
				bis = new BufferedInputStream(is);
				Bitmap bitmap = BitmapFactory.decodeStream(bis);
				bitmap.recycle();
			} catch (Exception e) {
				// Try to recover
			} finally {
				try {
					if (bis != null) {
						bis.close();
					}
					if (is != null) {
						is.close();
					}
					cursor.close();
					projection = null;
				} catch (Exception e) {
				}
			}
		}
	}

	/*-------------methods--------------*/
	private void setupViews() {
		gridView.setClipToPadding(false);
		gridView.setOnItemClickListener(MainActivity.this);
		imageAdapter = new ImageAdapter(getApplicationContext());
		gridView.setAdapter(imageAdapter);
		
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				Variables.currentIndex = position;
				MainActivity.this.currentPhotoActivity.setView();
				
			}
		});
	}

	private void loadImages() {
		final Object data = getLastNonConfigurationInstance();
		if (data == null) {
			new LoadImagesFromSDCard().execute();
		} else {
			final Bitmap[] photos = (Bitmap[]) data;
			if (photos.length == 0) {
				new LoadImagesFromSDCard().execute();
			}
			for (Bitmap photo : photos) {
				addImage(photo);
			}
		}
	}

	private void addImage(Bitmap... value) {
		for (Bitmap image : value) {
			imageAdapter.addPhoto(image);
			imageAdapter.notifyDataSetChanged();
			Variables.photoPagerAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		final GridView grid = gridView;
		final int count = grid.getChildCount();
		final Bitmap[] list = new Bitmap[count];

		for (int i = 0; i < count; i++) {
			final ImageView v = (ImageView) grid.getChildAt(i);
			list[i] = ((BitmapDrawable) v.getDrawable()).getBitmap();
		}

		return list;
	}

	/*----------------new class-------------------*/
	class ImageAdapter extends BaseAdapter {

		private Context mContext;

		public ImageAdapter(Context context) {
			mContext = context;
		}

		public void addPhoto(Bitmap photo) {
			Variables.listPhotos.add(photo);
		}

		public int getCount() {
			return Variables.listPhotos.size();
		}

		public Object getItem(int position) {
			return Variables.listPhotos.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final ImageView imageView;
			if (convertView == null) {
				imageView = new ImageView(mContext);
			} else {
				imageView = (ImageView) convertView;
			}
			imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			imageView.setPadding(0, 0, 0, 0);
			imageView.setImageBitmap(Variables.listPhotos.get(position));

			return imageView;
		}
	}

	class LoadImagesFromSDCard extends AsyncTask<Object, Bitmap, Object> {

		/**
		 * Load images from SD Card in the background, and display each image on
		 * the screen.
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected Object doInBackground(Object... params) {
			
			Bitmap bitmap = null;
			Bitmap newBitmap = null;
			Uri uri = null;

			// Set up an array of the Thumbnail Image ID column we want
			String[] projection = { MediaStore.Images.Thumbnails._ID };
			// Create the cursor pointing to the SDCard
			Cursor cursor = managedQuery(
					MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
					projection, // Which columns to return
					null, // Return all rows
					null, null);
			int columnIndex = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);

			int size = cursor.getCount();
			
			int imageID = 0;
			MyExif exif = null;
			PhotoProperties photoProperties = null;
			
			for (int i = size - 1; i >= 0; i--) {
				cursor.moveToPosition(i);
				imageID = cursor.getInt(columnIndex);
				
				uri = Uri.withAppendedPath(
						MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""
								+ imageID);
				exif = new MyExif(Uri.parse("content://media/external/images/media/" + imageID), MainActivity.this);
				try {
					photoProperties = new PhotoProperties(exif.getExifinterface(), exif.getPath());
				} catch (ParseException e1) {
					e1.printStackTrace();
				}
				Variables.listProperties.add(photoProperties);
								
				try {
					bitmap = BitmapFactory.decodeStream(getContentResolver()
							.openInputStream(uri));
					if (bitmap != null) {
						newBitmap = Bitmap.createScaledBitmap(bitmap,
								display.getWidth() / 3 - 10,
								display.getHeight() / 5, false);
						bitmap.recycle();
						if (newBitmap != null) {
							publishProgress(newBitmap);
						}
					}
				} catch (IOException e) {
					// Error fetching image, try to recover
				}
			}
			cursor.close();
			return null;
		}

		/**
		 * Add a new Bitmap in the images grid.
		 * 
		 * @param value
		 *            The image.
		 */
		@Override
		public void onProgressUpdate(Bitmap... value) {
			addImage(value);
		}

		/**
		 * Set the visibility of the progress bar to false.
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Object result) {
			setProgressBarIndeterminateVisibility(false);
		}
	}

	/*-------------------helpers capture--------------------*/
	private void dispatchTakePictureIntent(int actionCode) {

		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		File f = null;

		try {
			f = setUpPhotoFile();
			mCurrentPhotoPath = f.getAbsolutePath();
			takePictureIntent
					.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		} catch (IOException e) {
			e.printStackTrace();
			f = null;
			mCurrentPhotoPath = null;
		}

		startActivityForResult(takePictureIntent, actionCode);
	}

	private File setUpPhotoFile() throws IOException {

		File f = createImageFile();
		mCurrentPhotoPath = f.getAbsolutePath();

		return f;
	}

	@SuppressLint("SimpleDateFormat")
	private File createImageFile() throws IOException {
		// Create an image file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		File albumF = getAlbumDir();
		File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX,
				albumF);
		return imageF;
	}

	private File getAlbumDir() {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {

			storageDir = mAlbumStorageDirFactory
					.getAlbumStorageDir(getAlbumName());

			if (storageDir != null) {
				if (!storageDir.mkdirs()) {
					if (!storageDir.exists()) {
						Log.d("ITEPU", "failed to create directory");
						return null;
					}
				}
			}

		} else {
			Log.v(getString(R.string.app_name),
					"External storage is not mounted READ/WRITE.");
		}

		return storageDir;
	}

	private String getAlbumName() {
		return "Electric";
	}

	public static boolean isIntentAvailable(Context context, String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
				PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}
	
}